package cn.b.sky.mes.andon.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import cn.b.sky.mes.andon.dao.AndonDao;
import cn.b.sky.mes.andon.dao.AndonRunDao;
import cn.b.sky.mes.andon.dao.MessageRuleAndonAssignDao;
import cn.b.sky.mes.andon.dao.MessageRuleDao;
import cn.b.sky.mes.andon.dao.MessageRuleItemDao;
import cn.b.sky.mes.andon.dao.MessageTriggeredDao;
import cn.b.sky.mes.andon.model.Andon;
import cn.b.sky.mes.andon.model.AndonRun;
import cn.b.sky.mes.andon.model.MessageRule;
import cn.b.sky.mes.andon.model.MessageRuleItem;
import cn.b.sky.mes.andon.model.MessageTriggered;
import cn.b.sky.mes.andon.model.condition.MessageRuleItemCondition;
import cn.b.sky.mes.andon.service.AndonMessageService;
import cn.b.sky.message.model.MessageUser;
import cn.b.sky.message.service.MessageService;

import com.alibaba.fastjson.JSONObject;

/**
 * <strong>Title : AndonMessageServiceImpl.java<br></strong>
 * <strong>Package : cn.b.sky.mes.andon.service.impl<br></strong>
 * <strong>Description : </strong>暗灯消息通知业务实现类<br> 
 * <strong>Create on : 2016年10月19日 下午5:13:33<br></strong>
 * <p>
 * @author ShiYing.Ke<br>
 * @version <strong>v1.0.0</strong><br>
 * <br>
 * <strong>修改历史:</strong><br>
 * 修改人|修改日期|修改描述<br>
 * -------------------------------------------<br>
 * <br>
 * <br>
 */
@Service("andonMessageService")
public class AndonMessageServiceImpl implements AndonMessageService {
	
	private static final Logger LOG = LoggerFactory
			.getLogger(AndonMessageServiceImpl.class);
	
	@Autowired
	MessageRuleDao messageRuleDao;
	
	@Autowired
	MessageRuleItemDao messageRuleItemDao;
	
	@Autowired
	MessageRuleAndonAssignDao messageRuleAndonAssignDao;
	
	@Autowired
	AndonDao andonDao;
	
	@Autowired
	AndonRunDao andonRunDao;
	
	@Autowired
	MessageService messageService;
	
	@Autowired
	MessageTriggeredDao messageTriggeredDao;

	@Override
	public void doSendAndonMessage() {
		// 获取所有消息通知规则
		List<MessageRule> allMsgRule = messageRuleDao.selectMessageRules();
		if(!CollectionUtils.isEmpty(allMsgRule)){
			for(MessageRule rule : allMsgRule){
				// 获取规则明细列表
				MessageRuleItemCondition item = new MessageRuleItemCondition();
				item.setSiteCode(rule.getSiteCode());
				item.setRuleCode(rule.getRuleCode());
				List<MessageRuleItem> itemList = messageRuleItemDao.selectMessageRuleItemsByCondition(item);
				// 获取关联暗灯主表
				List<Andon> andonList = null;
				// 判断是否全部
				if(rule.getAllAndonsFlag() != null && rule.getAllAndonsFlag().intValue() == 1){
					andonList = andonDao.getAllAndonList();
				} else{
					andonList = andonDao.selectAndonListByMessageRule(rule);
				}
				// 根据主表取暗灯明细表
				List<AndonRun> allAndonRunList = new ArrayList<AndonRun>();
				if(!CollectionUtils.isEmpty(andonList)){
					for(Andon andon : andonList){
						List<AndonRun> andonRunList = andonRunDao.selectAndonRunListByAndon(andon);//TODO 需优化，数量太大
						allAndonRunList.addAll(andonRunList);
					}
					// 循环消息规则明细
					for(MessageRuleItem mItem : itemList){
						try {
							sendAndonMessage(mItem, allAndonRunList);
						} catch (Exception e) {
							LOG.error("消息规则id：{}，发送暗灯消息通知异常：{}", mItem.getId(), e);
						}
					}
				}
			}
		}
	}

	/**
	 * <strong>Title : sendAndonMessage<br></strong>
	 * <strong>Description : </strong>发送符合规则的暗灯消息通知<br> 
	 * <strong>Create on : 2016年10月20日 下午5:30:23<br></strong>
	 * <p>
	 * @param messageRuleItem
	 * @param andonRunList
	 * void
	 * @throws 
	 * @author ShiYing.Ke<br>
	 * @version <strong>v1.0.0</strong><br>
	 * <br>
	 * <strong>修改历史:</strong><br>
	 * 修改人 | 修改日期 | 修改描述<br>
	 * -------------------------------------------<br>
	 * <br>
	 * <br>
	 */
	private void sendAndonMessage(MessageRuleItem messageRuleItem,
			List<AndonRun> andonRunList) {
		Date now = new Date();
		// 判断是否在通知时段内
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
		String nowTime = sdf.format(now);
		long nowTimeNumeric = Long.valueOf(nowTime.replaceAll("[-\\s:]",""));
		long periodStartNumeric = Long.valueOf(messageRuleItem.getPeriodStart().replaceAll("[-\\s:]",""));
		long periodEndNumeric = Long.valueOf(messageRuleItem.getPeriodEnd().replaceAll("[-\\s:]",""));
		if(nowTimeNumeric >= periodStartNumeric && nowTimeNumeric <= periodEndNumeric){
			// 计时起点字段
			String startCode = messageRuleItem.getTimerStartEcode();
			// 升级时限
			long timeInterval = messageRuleItem.getTimeInterval() * 1000L;
			// 监控状态
			String statusECode = messageRuleItem.getStatusEcode() == null ? "" : messageRuleItem.getStatusEcode();
			// 接收用户
			String[] receiveUsers = messageRuleItem.getReceiveUser().split(",");
			// 消息编号
			String messageCode = messageRuleItem.getMessageCode();
			long nowMillis = now.getTime();
			long stMillis = nowMillis;
			for(AndonRun ar : andonRunList){
				// 判断是否已发送消息
				MessageTriggered m = messageTriggeredDao.selectMessageTriggered(ar.getId(), messageRuleItem.getId());
				if(null != m){
					continue;
				}
				if("SWITCHONDATETIME".equals(startCode)){
					// 启动时间计时
					stMillis = ar.getSwitchOnDateTime().getTime();
				} else if("SWITCHOFFDATETIME".equals(startCode)){
					// 关闭时间计时
					stMillis = ar.getSwitchOffDateTime().getTime();
				} else if("RESPONDDATETIME".equals(startCode)){
					// 响应时间计时
					stMillis = ar.getRespondDateTime().getTime();
				}
				stMillis += timeInterval;
				if(statusECode.equals(ar.getStatusECode()) && stMillis >= nowMillis){
					// 发送消息
					MessageUser messageUser = new MessageUser();
					messageUser.setUserList(receiveUsers);
					Map<String, String> map = (Map<String, String>) JSONObject.toJSON(ar);
					messageService.sendMessageToGivenUser(ar.getSiteCode(), 
					    messageCode, messageUser, map);
				}
			}
		}
	}

}
